package base.common;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test3List {
	
	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		Collections.addAll(list, "0", "1", "2", "3", "4", "10", "21");
		System.out.println("初始list:" + list);
		
		list.add("new item");
		System.out.println("添加一个项目:" + list);
		
		String str = list.remove(0);
		System.out.println("删除索引0的项目:" + list + ", 被删除的元素是：" + str);
		
		list.addAll(list);
		System.out.println("list中添加list:" + list);
		
		int idx = list.indexOf("4");
		System.out.println("获取查找元素的第一个索引:" + idx);
		System.out.println("判断list集合中是否存在3:" + list.contains("3"));
		System.out.println("判断list集合中是否存在9:" + list.contains("9"));
		
		List<String> list2 = new ArrayList<String>();
		Collections.addAll(list2, "1", "2"); 
		System.out.println("判断list集合中包含多个对象(\"1\", \"2\"):" + list.containsAll(list2));
		
		System.out.println("使用迭代器遍历list：");
		Iterator<String> it = list.iterator();
		while(it.hasNext()) {
			System.out.println(it.next());
		}
		
		Object[] arr = list.toArray();
		System.out.println("list转数组:" + arr);
		
		list.set(0, "first item");
		System.out.println("根据索引添加元素:" + list);
		
		list.sort(Comparator.naturalOrder());
		System.out.println("升序排序:" + list);
		
		list.sort(Comparator.reverseOrder());
		System.out.println("降序排序:" + list);
		
		
		list.sort(new Comparator<String>() {
			@Override
			public int compare(String arg0, String arg1) {
				if(arg0.compareTo(arg1) == 0)
					return 0;
				if(arg0.compareTo(arg1) > 0)
					return 1;
				if(arg0.compareTo(arg1) < 0)
					return -1;
				return 0;
			}
			
		});
		System.out.println("自定义排序:" + list);
		
		
		Collections.sort(list, new Comparator<String>() {
			@Override
			public int compare(String arg0, String arg1) {
				Pattern pattern = Pattern.compile("^[0-9]*$");
				Matcher matcher0 = pattern.matcher(arg0);
				Matcher matcher1 = pattern.matcher(arg1);
				if(!matcher0.matches() || !matcher1.matches()) {
					return arg0.compareTo(arg1);
				}
				
				int i0 = Integer.valueOf(arg0);
				int i1 = Integer.valueOf(arg1);
				
				if(i0 == i1)
					return 0;
				if(i0 > i1)
					return 1;
				if(i0 < i1)
					return -1;
				return 0;
			}
        });
		System.out.println("自定义排序2:" + list);
		
	}

}
